package com.syezon.wifikey.home;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.hodanet.appadvplatclient.ReportAgent;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.syezon.android.base.utils.LogUtils;
import com.syezon.wifikey.R;
import com.syezon.wifikey.about.AboutActivity;
import com.syezon.wifikey.ad.AdPositionEnum;
import com.syezon.wifikey.ad.CommonAdViewModel;
import com.syezon.wifikey.ad.ConfigService;
import com.syezon.wifikey.ad.InterAd;
import com.syezon.wifikey.ad.InterAdConfig;
import com.syezon.wifikey.ad.SimuAdViewModel;
import com.syezon.wifikey.ad.SimuClickAdInfo;
import com.syezon.wifikey.analysis.AnalysisHelper;
import com.syezon.wifikey.analysis.event.EventEnum;
import com.syezon.wifikey.base.BaseActivity;
import com.syezon.android.base.utils.ToastUtils;
import com.syezon.wifikey.channel.ChannelConfig;
import com.syezon.wifikey.config.AppConfig;
import com.syezon.wifikey.feedback.FeedBackAndHelpActivity;
import com.syezon.wifikey.hot.HotFragment;
import com.syezon.wifikey.news.NewsListFragment;
import com.syezon.wifikey.news.ResultInfo;
import com.syezon.wifikey.pwd.PwdFragment;
import com.syezon.wifikey.redbag.BoxFragment;
import com.syezon.wifikey.setting.GradeConfig;
import com.syezon.wifikey.setting.GradeNewDialog;
import com.syezon.wifikey.setting.MeFragment;
import com.syezon.wifikey.redbag.PacketFragment;
import com.syezon.wifikey.setting.SettingActivity;
import com.syezon.wifikey.utils.WifiUtil;
import com.syezon.wifikey.wifi.WiFiFragment;
import com.syezon.wifikey.wifi.WifiConnectService;
import com.syezon.wifikey.wifi.WifiListUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements InterAd.OnShowSelfADListener{

    public static final String GOOD_COMMENT_URL = "http://sj.qq.com/myapp/detail.htm?apkName=com.syezon.wifikey";

    public static final long DURATION = 2000L;
    public static final int TAB_INDEX_WIFI = 0;
    public static final int TAB_INDEX_NEWS = 1;
    public static final int TAB_INDEX_BOX = 2;
    public static final int TAB_INDEX_PWD = 3;
    public static final int TAB_INDEX_PACK = 4;
    public static final int TAB_INDEX_HOT = 5;
    public static final int TAB_INDEX_SETTING = 6;

    @BindView(R.id.drawerMenu)
    DrawerLayout mDrawMenu;
    @BindView(R.id.iv_tab_wifi)
    ImageView mIvTabWiFi;
    @BindView(R.id.tv_tab_wifi)
    TextView mTvTabWiFi;
    @BindView(R.id.iv_tab_pwd)
    ImageView mIvTabPwd;
    @BindView(R.id.tv_tab_pwd)
    TextView mTvTabPwd;
    @BindView(R.id.iv_tab_pack)
    ImageView mIvTabPack;
    @BindView(R.id.tv_tab_pack)
    TextView mTvTabPack;
    @BindView(R.id.iv_tab_news)
    ImageView mIvTabNews;
    @BindView(R.id.tv_tab_news)
    TextView mTvTabNews;
    @BindView(R.id.iv_tab_box)
    ImageView mIvTabBox;
    @BindView(R.id.tv_tab_box)
    TextView mTvTabBox;
    @BindView(R.id.iv_tab_hot)
    ImageView mIvTabHot;
    @BindView(R.id.tv_tab_hot)
    TextView mTvTabHot;
    @BindView(R.id.iv_tab_setting)
    ImageView mIvTabSetting;
    @BindView(R.id.tv_tab_setting)
    TextView mTvTabSetting;

    @BindView(R.id.view_red_dot)
    View mViewNewsRedTip;

    @BindView(R.id.ll_tab_pack)
    LinearLayout mLlPacket;
    @BindView(R.id.ll_tab_box)
    LinearLayout mLlBox;

    @BindView(R.id.rl_tab_news)
    RelativeLayout mRlNewsTab;

    @BindView(R.id.rl_menu_ad)
    RelativeLayout mRlMenuAd;
    @BindView(R.id.iv_menu_ad)
    ImageView mIvMenuAd;
    //    @BindView(R.id.view_menu_red_tip)
//    View mViewMenuRedTip;
    @BindView(R.id.tv_menu_ad)
    TextView mTvMenuAd;

    @BindView(R.id.tv_menu_connected_wifi_ssid)
    TextView mTvConnectedWifiSsid;
    @BindView(R.id.tv_menu_wifi_connected_state)
    TextView mTvConnecteState;
    @BindView(R.id.tv_menu_ip_address)
    TextView mTvConnectedIp;


    private WiFiFragment mWifiFragment;
    private PwdFragment mPwdFragment;
    private PacketFragment mPacketFragment;
    private HotFragment mHotFragment;
    private NewsListFragment mNewsFragment;
    private BoxFragment mBoxFragment;
    private MeFragment mMeFragment;

    private int mMenuAdIndex;
    private boolean mCanShowMenuTip;
    private List<AdInfo> mMenuAdList = new ArrayList<>();

    private int mInsertAdIndex;
    private List<AdInfo> mInsertAdList = new ArrayList<>();
    private InsertFloatAdDialog mInsertFloatDialog;
    private boolean mIsShowInsertAd;


    private InterAd mInterAd ;
    private CommonAdViewModel mPopAdViewModel;

    private PopFloatAdDialog selfAdDialog;
    @BindView(R.id.fl_web_container)
    FrameLayout mFlWebContainer;
    @BindView(R.id.fl_fake_container)
    FrameLayout mFlFakeWebContainer;
    WebView mWebGhost;
    private int mGhostWebAdIndex;
    private AdInfo mCurrentGhostAd;
    private List<AdInfo> mGhostWebAdList = new ArrayList<>();
    private CommonAdViewModel mGhostAdViewModel;

    private int mCurrentIndex = -1;
    private long mBackPressTime;

    private Runnable mShowGradeRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                boolean canShowGradeNew = GradeConfig.canShowGradeNew();
                Activity topActivity = ActivityUtils.getTopActivity();
                if (canShowGradeNew && topActivity != null && !topActivity.isFinishing()) {
                    GradeNewDialog.showGrade(topActivity, null);
                }
            } catch (Exception e) {

            }
        }
    };
    WebView mFakeWeb;
    private SimuClickAdInfo mSimuAdInfo;
    private Handler handler = new Handler();
    private Scroller scroller;
    private Handler mHandler = new Handler();
    private SimuAdViewModel mFakeAdViewModel;
    private Runnable mScrollTask = new Runnable() {
        @Override
        public void run() {
            if (scroller.computeScrollOffset()) {
                mFakeWeb.scrollTo(0, scroller.getCurrY());
                mHandler.postDelayed(mScrollTask, 16);
            } else {
                mHandler.removeCallbacks(mScrollTask);
            }
        }
    };
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fragment wifiFragment = getSupportFragmentManager().findFragmentByTag(WiFiFragment.class.getSimpleName());
        if (wifiFragment != null) {
            mWifiFragment = (WiFiFragment) wifiFragment;
        }
        Fragment pwdFragment = getSupportFragmentManager().findFragmentByTag(PwdFragment.class.getSimpleName());
        if (pwdFragment != null) {
            mPwdFragment = (PwdFragment) pwdFragment;
        }
        Fragment packetFragment = getSupportFragmentManager().findFragmentByTag(PacketFragment.class.getSimpleName());
        if (pwdFragment != null) {
            mPacketFragment = (PacketFragment) packetFragment;
        }
        Fragment newsFragment = getSupportFragmentManager().findFragmentByTag(NewsListFragment.class.getSimpleName());
        if (newsFragment != null) {
            mNewsFragment = (NewsListFragment) newsFragment;
        }
        Fragment boxFragment = getSupportFragmentManager().findFragmentByTag(BoxFragment.class.getSimpleName());
        if (boxFragment != null) {
            mBoxFragment = (BoxFragment) boxFragment;
        }
        Fragment hotFragment = getSupportFragmentManager().findFragmentByTag(HotFragment.class.getSimpleName());
        if (hotFragment != null) {
            mHotFragment = (HotFragment) hotFragment;
        }
        Fragment settingFragment = getSupportFragmentManager().findFragmentByTag(MeFragment.class.getSimpleName());
        if (settingFragment != null) {
            mMeFragment = (MeFragment) settingFragment;
        }
        init();
    }

    private void showResult(boolean result) {
        try {
            ResultInfo intentArgs = getIntent().getParcelableExtra(ResultHelper.ARG_RESULT_INFO);
            if (intentArgs != null && result) {
                showNewsTab(intentArgs);
            } else {
                if (!AppConfig.isFirst() && WifiUtil.isWifiConnected()) {
                    String wifiSSID = WifiUtil.getWifiSSID();
                    ResultInfo resultInfo = new ResultInfo();
                    resultInfo.setResultType(ResultInfo.TYPE_SHOW_WIFI_INFO);
                    resultInfo.setSsid(wifiSSID);
                    showNewsTab(resultInfo);
                }
            }
        } catch (Exception e) {

        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        showResult(true);
    }

    public void showNewsTab(ResultInfo resultInfo) {
        try {
            if (TAB_INDEX_NEWS != mCurrentIndex) {
                resetBottomView();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                if (mWifiFragment != null) {
                    fragmentTransaction.hide(mWifiFragment);
                }
                if (mNewsFragment != null) {
                    fragmentTransaction.hide(mNewsFragment);
                }
                if (mPwdFragment != null) {
                    fragmentTransaction.hide(mPwdFragment);
                }
                if (mPacketFragment != null) {
                    fragmentTransaction.hide(mPacketFragment);
                }
                if (mBoxFragment != null) {
                    fragmentTransaction.hide(mBoxFragment);
                }
                if (mHotFragment != null) {
                    fragmentTransaction.hide(mHotFragment);
                }
                if (mMeFragment != null) {
                    fragmentTransaction.hide(mMeFragment);
                }

                if (mNewsFragment == null) {
                    mNewsFragment = NewsListFragment.newInstance(resultInfo);
                    fragmentTransaction.add(R.id.fl_tab_content, mNewsFragment, NewsListFragment.class.getSimpleName());
                } else {
                    fragmentTransaction.show(mNewsFragment);
                    mNewsFragment.showResult(resultInfo);
                    showMenuRedTip();
                }
                mCurrentIndex = TAB_INDEX_NEWS;
                mIvTabNews.setImageResource(R.drawable.ic_tab_news_p);
                mTvTabNews.setTextColor(getResources().getColor(R.color.color_tab_p));
                AnalysisHelper.onEvent(EventEnum.NEWS_FRAGMENT_SHOW.eventId);
                AppConfig.saveNewsClickDay(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
                mViewNewsRedTip.setVisibility(View.GONE);
                fragmentTransaction.commitAllowingStateLoss();
            } else {
                mNewsFragment.showResult(resultInfo);
            }

        } catch (Exception e) {

        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        LogUtils.dTag(TAG_LOG, "onSaveInstanceState");
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.dTag(TAG_LOG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.dTag(TAG_LOG, "onStop");
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViewsAndEvents() {

    }

    private void init() {
        WifiConnectService.getInstance();
        WifiListUtils.getInstance();
        int newsClickDay = AppConfig.getNewsClickDay();
        if (newsClickDay != Calendar.getInstance().get(Calendar.DAY_OF_MONTH)) {
            mViewNewsRedTip.setVisibility(View.VISIBLE);
        } else {
            mViewNewsRedTip.setVisibility(View.GONE);
        }
//        if (ConfigService.getInstance().isShowSelfAd()) {
//            mLlBox.setVisibility(View.VISIBLE);
//        } else {
//            mLlBox.setVisibility(View.GONE);
//        }
//        WifiConnectService.getInstance().getShowConnectedAdLiveData().observe(this, new Observer<Boolean>() {
//            @Override
//            public void onChanged(@Nullable Boolean aBoolean) {
//                if (aBoolean) {
//                    ToastUtils.showShort("网络可用，看看资讯吧");
//                    setTab(TAB_INDEX_NEWS);
//                    showWifiConnectedAd();
//                }
//            }
//        });
        //插屏
        mPopAdViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.SCREEN_INSERT.getUmengEventId(), CommonAdViewModel.class);
        mPopAdViewModel.setAdPositionEnum(AdPositionEnum.SCREEN_INSERT);
        mPopAdViewModel.getAdLiveData().observe(this, new Observer<List<AdInfo>>() {
            @Override
            public void onChanged(@Nullable List<AdInfo> adInfos) {
                if (adInfos != null) {
                    InterAdConfig.setAdList(adInfos);
                    if (mInterAd == null) {
                        mInterAd = new InterAd(MainActivity.this);
                        mInterAd.setAdInfos(adInfos);
                        mInterAd.setOnShowSelfADListener(MainActivity.this);
                    }
                    mInterAd.loadInterAd();
                }
            }
        });
        mDrawMenu.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        mDrawMenu.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
//                initWifiInfo();
//                showMenuAd();
            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
                showMenuRedTip();
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        initTabAd();
//        if (ConfigService.getInstance().isShowCSJAd()) {
//            mInterAd.loadInterAd();
//        }
        if (AppConfig.isShowNewsTab()) {
            mRlNewsTab.setVisibility(View.VISIBLE);
        } else {
            mRlNewsTab.setVisibility(View.GONE);
        }
        setTab(TAB_INDEX_WIFI);
        showResult(false);
        AppConfig.setFirst(false);
    }

    private void triggerGrade() {
        getHandler().removeCallbacks(mShowGradeRunnable);
        getHandler().postDelayed(mShowGradeRunnable, 2000);
    }

    private void initWifiInfo() {
        if (WifiUtil.isWifiConnected()) {
            String wifiSSID = WifiUtil.getWifiSSID();
            if (wifiSSID != null) {
                if (wifiSSID.contains("unknown ssid")) {
                    wifiSSID = "- - -";
                }
                wifiSSID = wifiSSID.replace("\"", "");
            } else {
                wifiSSID = "- - -";
            }
            mTvConnectedWifiSsid.setText(wifiSSID);
            mTvConnecteState.setText("已成功连接");
            mTvConnecteState.setVisibility(View.VISIBLE);
            WifiInfo wifiInfo = WifiUtil.getWifiInfo();
            int ip = wifiInfo != null ? wifiInfo.getIpAddress() : 0;
            String ipString = WifiUtil.intToIp(ip);
            mTvConnectedIp.setText("IP: " + ipString);
        } else {
            mTvConnectedWifiSsid.setText("WiFi连接已断开");
            mTvConnecteState.setText("未连接");
            mTvConnectedIp.setText("IP: " + "0.0.0.0");
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        switchAd();
//        showTopFloatAd();
    }

    private void switchAd() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mInterAd != null) {
            mInterAd.destroy();
        }
        try {
            if (mWebGhost != null) {
                mWebGhost.stopLoading();
                // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
                mWebGhost.getSettings().setJavaScriptEnabled(false);
                mWebGhost.clearHistory();
                mWebGhost.clearView();
                mWebGhost.removeAllViews();
                mWebGhost.destroy();
                mFlWebContainer.removeAllViews();
            }
        } catch (Exception e) {

        }
        ConfigService.getInstance().reset();
        WifiListUtils.getInstance().reset();
        WifiConnectService.getInstance().reset();
    }


    public void showMenuAd() {
//        int size = mMenuAdList.size();
//        if (size > 0) {
//            final AdInfo adInfo = mMenuAdList.get(mMenuAdIndex % size);
//            ImageLoader.getInstance().displayImage(MainActivity.this, adInfo.getPic(), mIvMenuAd);
//            mTvMenuAd.setText(adInfo.getName());
//            mRlMenuAd.setVisibility(View.VISIBLE);
//            AnalysisHelper.onAdEvent(AdPositionEnum.MENU_LIST, AnalysisHelper.EVENT_EXT_SHOW, adInfo.getId());
//            mRlMenuAd.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    WebHelper.showAd(MainActivity.this, adInfo.getUrl(), adInfo.getName());
//                    AnalysisHelper.onAdEvent(AdPositionEnum.MENU_LIST, AnalysisHelper.EVENT_CLICK, adInfo.getId());
//                    AdConfig.setClick(adInfo.getId(), true);
//                }
//            });
//            mMenuAdIndex++;
//            if (mMenuAdIndex > (Integer.MAX_VALUE - 10)) {
//                mMenuAdIndex = 0;
//            }
//        } else {
//            mRlMenuAd.setVisibility(View.GONE);
//        }
    }

    private void showWifiConnectedAd() {
        if (!mIsShowInsertAd && mInsertAdList.size() > 0) {
//            Random random = new Random();
//            AdInfo adInfo = mInsertAdList.get(random.nextInt(mInsertAdList.size()));
//            if (mInsertFloatDialog != null && mInsertFloatDialog.isShowing()) {
//                return;
//            }
//            if (mInsertFloatDialog == null) {
//                mInsertFloatDialog = new InsertFloatAdDialog(this, R.style.Dialog_AD);
//            }
//            mInsertFloatDialog.setAdInfo(adInfo);
//            mInsertFloatDialog.show();
//            mIsShowInsertAd = true;
        }
    }

    @OnClick({R.id.rl_menu_setting, R.id.rl_menu_feedback,
            R.id.rl_menu_good_comment, R.id.rl_menu_ad,
            R.id.rl_menu_about,
            R.id.ll_tab_wifi, R.id.rl_tab_news, R.id.ll_tab_pwd,
            R.id.ll_tab_pack, R.id.ll_tab_box, R.id.ll_tab_hot,
            R.id.ll_tab_setting
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_menu_setting:
                readyGo(SettingActivity.class);
                closeMenu();
                break;
            case R.id.rl_menu_feedback:
                readyGo(FeedBackAndHelpActivity.class);
                closeMenu();
                break;
            case R.id.rl_menu_good_comment:
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(GOOD_COMMENT_URL));
                ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
                if (resolveInfo != null) {
                    startActivity(intent);
                }
                closeMenu();
                break;
            case R.id.rl_menu_about:
                readyGo(AboutActivity.class);
                closeMenu();
                break;
            case R.id.ll_tab_wifi:
                setTab(TAB_INDEX_WIFI);
                triggerGrade();
                break;
            case R.id.rl_tab_news:
                showNewsTab(null);
                triggerGrade();
                break;
            case R.id.ll_tab_pwd:
                setTab(TAB_INDEX_PWD);
                break;
            case R.id.ll_tab_pack:
                setTab(TAB_INDEX_PACK);
                break;
            case R.id.ll_tab_box:
                setTab(TAB_INDEX_BOX);
                triggerGrade();
                break;
            case R.id.ll_tab_hot:
                setTab(TAB_INDEX_HOT);
                break;
            case R.id.ll_tab_setting:
                setTab(TAB_INDEX_SETTING);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mDrawMenu.isDrawerOpen(Gravity.LEFT)) {
                mDrawMenu.closeDrawer(Gravity.LEFT);
                return true;
            }
            long time = System.currentTimeMillis();
            if (time - mBackPressTime > DURATION) {
                mBackPressTime = time;
                ToastUtils.showShort("再按一下退出应用！");
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 重置底部视图
     */
    private void resetBottomView() {
        mIvTabWiFi.setImageResource(R.drawable.ic_tab_wifi_n);
        mTvTabWiFi.setTextColor(getResources().getColor(R.color.color_tab_n));
        mIvTabNews.setImageResource(R.drawable.ic_tab_news_n);
        mTvTabNews.setTextColor(getResources().getColor(R.color.color_tab_n));
        mIvTabPwd.setImageResource(R.drawable.ic_tab_pwd_n);
        mTvTabPwd.setTextColor(getResources().getColor(R.color.color_tab_n));
        mIvTabPack.setImageResource(R.drawable.ic_tab_pack_n);
        mTvTabPack.setTextColor(getResources().getColor(R.color.color_tab_n));
        mIvTabBox.setImageResource(R.drawable.ic_tab_box);
        mTvTabBox.setTextColor(getResources().getColor(R.color.color_tab_n));
        mIvTabHot.setImageResource(R.drawable.ic_tab_hot_n);
        mTvTabHot.setTextColor(getResources().getColor(R.color.color_tab_n));
        mIvTabSetting.setImageResource(R.drawable.ic_tab_setting_n);
        mTvTabSetting.setTextColor(getResources().getColor(R.color.color_tab_n));
    }


    /**
     * @param index 选中tab
     */
    private void setTab(int index) {
        if (index != mCurrentIndex) {
            resetBottomView();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            if (mWifiFragment != null) {
                fragmentTransaction.hide(mWifiFragment);
            }
            if (mNewsFragment != null) {
                fragmentTransaction.hide(mNewsFragment);
            }
            if (mPwdFragment != null) {
                fragmentTransaction.hide(mPwdFragment);
            }
            if (mPacketFragment != null) {
                fragmentTransaction.hide(mPacketFragment);
            }
            if (mBoxFragment != null) {
                fragmentTransaction.hide(mBoxFragment);
            }
            if (mHotFragment != null) {
                fragmentTransaction.hide(mHotFragment);
            }
            if (mMeFragment != null) {
                fragmentTransaction.hide(mMeFragment);
            }
            if (index == TAB_INDEX_WIFI) {
                if (mWifiFragment == null) {
                    mWifiFragment = WiFiFragment.newInstance();
                    fragmentTransaction.add(R.id.fl_tab_content, mWifiFragment, WiFiFragment.class.getSimpleName());
                } else {
                    fragmentTransaction.show(mWifiFragment);
                    //mWifiFragment.switchAd(false);
                    mCanShowMenuTip = true;
                    showMenuRedTip();
//                    showTopFloatAd();
                }
                mCurrentIndex = TAB_INDEX_WIFI;
                mIvTabWiFi.setImageResource(R.drawable.ic_tab_wifi_p);
                mTvTabWiFi.setTextColor(getResources().getColor(R.color.color_tab_p));
                AnalysisHelper.onEvent(EventEnum.WIFI_FRAGMENT_SHOW.eventId);
            }

            if (index == TAB_INDEX_PWD) {
                if (mPwdFragment == null) {
                    mPwdFragment = PwdFragment.newInstance();
                    fragmentTransaction.add(R.id.fl_tab_content, mPwdFragment, PwdFragment.class.getSimpleName());
                } else {
                    fragmentTransaction.show(mPwdFragment);
                }
                mCurrentIndex = TAB_INDEX_PWD;
                mIvTabPwd.setImageResource(R.drawable.ic_tab_pwd_p);
                mTvTabPwd.setTextColor(getResources().getColor(R.color.color_tab_p));
                AnalysisHelper.onEvent(EventEnum.PWD_FRAGMENT_SHOW.eventId);
//                showTopFloatAd();
            }

            if (index == TAB_INDEX_PACK) {
                if (mPacketFragment == null) {
                    mPacketFragment = PacketFragment.newInstance();
                    fragmentTransaction.add(R.id.fl_tab_content, mPacketFragment, PacketFragment.class.getSimpleName());
                } else {
                    fragmentTransaction.show(mPacketFragment);
                }
                mCurrentIndex = TAB_INDEX_PACK;
                mIvTabPack.setImageResource(R.drawable.ic_tab_pack_p);
                mTvTabPack.setTextColor(getResources().getColor(R.color.color_tab_p));
                AnalysisHelper.onEvent(EventEnum.RED_PACKET_FRAGMENT_SHOW.eventId);
//                showTopFloatAd();
            }

            if (index == TAB_INDEX_BOX) {
                if (mBoxFragment == null) {
                    mBoxFragment = BoxFragment.newInstance();
                    fragmentTransaction.add(R.id.fl_tab_content, mBoxFragment, BoxFragment.class.getSimpleName());
                } else {
                    fragmentTransaction.show(mBoxFragment);
                }
                mCurrentIndex = TAB_INDEX_BOX;
                mIvTabBox.setImageResource(R.drawable.ic_tab_box);
                mTvTabBox.setTextColor(getResources().getColor(R.color.color_tab_p));
                AnalysisHelper.onEvent(EventEnum.BOX_FRAGMENT_SHOW.eventId);
//                showTopFloatAd();
            }

            if (index == TAB_INDEX_HOT) {
                if (mHotFragment == null) {
                    mHotFragment = HotFragment.newInstance();
                    fragmentTransaction.add(R.id.fl_tab_content, mHotFragment, HotFragment.class.getSimpleName());
                } else {
                    fragmentTransaction.show(mHotFragment);
                }
                mCurrentIndex = TAB_INDEX_HOT;
                mIvTabHot.setImageResource(R.drawable.ic_tab_hot_p);
                mTvTabHot.setTextColor(getResources().getColor(R.color.color_tab_p));
            }

            if (index == TAB_INDEX_SETTING) {
                if (mMeFragment == null) {
                    mMeFragment = MeFragment.newInstance();
                    fragmentTransaction.add(R.id.fl_tab_content, mMeFragment, MeFragment.class.getSimpleName());
                } else {
                    fragmentTransaction.show(mMeFragment);
                }
                mCurrentIndex = TAB_INDEX_SETTING;
                mIvTabSetting.setImageResource(R.drawable.ic_tab_setting_p);
                mTvTabSetting.setTextColor(getResources().getColor(R.color.color_tab_p));
            }
            fragmentTransaction.commitAllowingStateLoss();
        } else {
        }
    }

    private void showMenuRedTip() {
//        if (mMenuAdList.size() > 0 && mCanShowMenuTip) {
//            AdInfo adInfo = mMenuAdList.get(mMenuAdIndex % mMenuAdList.size());
//            boolean clicked = AdConfig.isClicked(adInfo.getId());
//            if (!clicked) {
//                mViewMenuRedTip.setVisibility(View.VISIBLE);
//            } else {
//                mViewMenuRedTip.setVisibility(View.GONE);
//            }
//        } else {
//            mViewMenuRedTip.setVisibility(View.GONE);
//        }
    }

    private void openMenu() {
        if (!mDrawMenu.isDrawerOpen(Gravity.LEFT)) {
            mDrawMenu.openDrawer(Gravity.LEFT);
        }
    }

    private void closeMenu() {
        if (mDrawMenu.isDrawerOpen(Gravity.LEFT)) {
            mDrawMenu.closeDrawer(Gravity.LEFT);
        }
    }

    private void initTabAd() {
        mGhostAdViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.GHOST_WEB.getUmengEventId(), CommonAdViewModel.class);
        mGhostAdViewModel.setAdPositionEnum(AdPositionEnum.GHOST_WEB);
        mGhostAdViewModel.getAdLiveData().observe(this, new Observer<List<com.hodanet.appadvplatclient.ad.AdInfo>>() {
            @Override
            public void onChanged(@Nullable List<com.hodanet.appadvplatclient.ad.AdInfo> adInfos) {
                mGhostWebAdList.clear();
                if (adInfos != null) {
                    mGhostWebAdList.addAll(adInfos);
                }
                showGhostWebAd();
            }
        });
        mFakeAdViewModel = ViewModelProviders.of(this).get(SimuAdViewModel.class);
        mFakeAdViewModel.getAdLiveData().observe(this, new Observer<SimuClickAdInfo>() {
            @Override
            public void onChanged(@Nullable SimuClickAdInfo simuClickAdInfo) {
                mSimuAdInfo = null;
                if (simuClickAdInfo != null) {
                    mSimuAdInfo = simuClickAdInfo;
                }
                showFakeWebAd();
            }
        });
    }
    private void showFakeWebAd() {
        try {
            if (mSimuAdInfo != null) {
                AdInfo adInfo = mSimuAdInfo.getAdInfo();
                if (adInfo != null) {
                    ReportAgent.reportAdvClick(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }
                initFakeWebView();
                mFakeWeb.loadUrl(mSimuAdInfo.getUrl());
            }
        } catch (Exception e) {

        }
    }
    private void initFakeWebView() {
        try {
            mFlFakeWebContainer.removeAllViews();
            if (mFakeWeb != null) {
                mFakeWeb.stopLoading();
                // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
                mFakeWeb.getSettings().setJavaScriptEnabled(false);
                mFakeWeb.clearHistory();
                mFakeWeb.clearView();
                mFakeWeb.removeAllViews();
                mFakeWeb.destroy();
            }
            mFakeWeb = new WebView(this);
            // 设置Client
            mFlFakeWebContainer.addView(mFakeWeb, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            mFakeWeb.setWebViewClient(new WebViewClient() {

                private int step = 0;
                private boolean stop = false;

                @Override
                public void onPageFinished(final WebView view, String url) {
                    super.onPageFinished(view, url);
                    try {
                        if (!stop && mSimuAdInfo != null) {
                            if (step == 0) {
                                SimuAdViewModel.reportSimuAd(mSimuAdInfo.getUrlId(), SimuClickAdInfo.SimuStep.OPTYPE_OPEN_URL, mSimuAdInfo.getCid());
                            }
                            final Map<Integer, SimuClickAdInfo.SimuStep> simuSteps = mSimuAdInfo.getSimuSteps();
                            if (simuSteps != null && !simuSteps.isEmpty()) {
                                step++;
                                SimuClickAdInfo.SimuStep simuStep = simuSteps.get(step);
                                if (simuStep != null) {
                                    int opType = simuStep.getOpType();
                                    if (SimuClickAdInfo.SimuStep.OPTYPE_FIRST_SLIDE == opType || SimuClickAdInfo.SimuStep.OPTYPE_SENCODE_SLIDE == opType) {
                                        int scrollHeight = getScrollHeight();
                                        int scrollTime = scrollHeight * 5;
                                        performScroll(simuStep.getDelayTime(), opType, scrollHeight, scrollTime);
                                        step++;
                                        SimuClickAdInfo.SimuStep nextStep = simuSteps.get(step);
                                        if (nextStep != null) {
                                            performOp(view, nextStep.getOpJsCode(), nextStep.getDelayTime() + simuStep.getDelayTime() + scrollTime, nextStep.getOpType(), mSimuAdInfo.getCid());
                                        }
                                    } else {
                                        SimuClickAdInfo.SimuStep nextStep = simuSteps.get(step);
                                        if (nextStep != null) {
                                            performOp(view, nextStep.getOpJsCode(), nextStep.getDelayTime(), nextStep.getOpType(), mSimuAdInfo.getCid());
                                        }
                                    }
                                } else {
                                    stop = true;
                                }
                            } else {
                                stop = true;
                            }
                        }
                    } catch (Exception e) {

                    }

                }

                private void performOp(final WebView webView, final String js, long delay, final int opType, final String cid) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            webView.loadUrl(js);
                            if (opType > 0) {
                                SimuAdViewModel.reportSimuAd(mSimuAdInfo.getUrlId(), opType, cid);
                            }
                        }
                    }, delay);
                }

                private void performScroll(long delay, final int opType, final int scrollRange, final int scrollTime) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            autoScrollWebView(scrollRange, scrollTime);
                            if (scrollRange > 0) {
                                SimuAdViewModel.reportSimuAd(mSimuAdInfo.getUrlId(), opType, mSimuAdInfo.getCid());
                            }
                        }
                    }, delay);
                }

            });
            mFakeWeb.setDownloadListener(new DownloadListener() {
                @Override
                public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

                }
            });
            mFakeWeb.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {

                }
            });
            WebSettings webSetting = mFakeWeb.getSettings();
            webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);
            webSetting.setJavaScriptEnabled(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            webSetting.setAllowFileAccess(true);
            webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            webSetting.setSupportZoom(true);
            webSetting.setBuiltInZoomControls(false);
            webSetting.setUseWideViewPort(true);
            webSetting.setSupportMultipleWindows(false);
            webSetting.setJavaScriptEnabled(true);
            webSetting.setLoadWithOverviewMode(true);
            webSetting.setAppCacheEnabled(true);
            webSetting.setDatabaseEnabled(true);
            webSetting.setDomStorageEnabled(true);
            webSetting.setGeolocationEnabled(true);
            webSetting.setAppCacheMaxSize(5 * 1024 * 1024);
            webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
            webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
            webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0).getPath());
            webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
            webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        } catch (Exception e) {

        }
    }
    private int getScrollHeight() {
        mFakeWeb.measure(0, 0);
        int measuredHeight = mFakeWeb.getMeasuredHeight();
        int height = mFakeWeb.getHeight();
        if (measuredHeight > height) {
            int scrollRange = measuredHeight - mFakeWeb.getHeight();
            if (scrollRange < height / 2) {
                return scrollRange;
            } else {
                int maxScrollRange = Math.min(scrollRange, height * 4);
                return height / 2 + new Random().nextInt(Math.abs(maxScrollRange - height / 2));
            }
        }
        return 0;
    }
    private void autoScrollWebView(int scrollHeight, int time) {
        if (scrollHeight > 0) {
            if (scroller != null) {
                scroller.abortAnimation();
            } else {
                scroller = new Scroller(this);
            }
            mFakeWeb.scrollTo(0, 0);
            scroller.startScroll(0, 0, 0, scrollHeight, time);
            mHandler.postDelayed(mScrollTask, 16);
        }
    }
    private void showGhostWebAd() {
        try {
            if (mGhostWebAdList.size() > 0) {
                final com.hodanet.appadvplatclient.ad.AdInfo adInfo = mGhostWebAdList.get(mGhostWebAdIndex % mGhostWebAdList.size());
                mCurrentGhostAd = adInfo;
                ReportAgent.reportAdvClick(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                initWebView();
                mWebGhost.loadUrl(adInfo.getUrl());
//                mWebGhost.loadUrl("http://www.xcxdh666.com/?cid=631245");
                mGhostWebAdIndex++;
            } else {
                mCurrentGhostAd = null;
            }
        } catch (Exception e) {

        }
    }

    private void initWebView() {
        try {
            mFlWebContainer.removeAllViews();
            if (mWebGhost != null) {
                mWebGhost.stopLoading();
                // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
                mWebGhost.getSettings().setJavaScriptEnabled(false);
                mWebGhost.clearHistory();
                mWebGhost.clearView();
                mWebGhost.removeAllViews();
                mWebGhost.destroy();
            }
            mWebGhost = new WebView(this);
            // 设置Client
            mFlWebContainer.addView(mWebGhost, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            mWebGhost.setWebViewClient(new WebViewClient() {

                boolean clicked = false;

                private int step = 1;

                private Handler handler = new Handler(Looper.getMainLooper());

                @Override
                public void onPageFinished(final WebView view, String url) {
                    super.onPageFinished(view, url);
//                    if (!clicked) {
//                        if (step == 1) {
//                            handler.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    view.loadUrl("javascript:location.href=document.getElementsByTagName('iframe')[0].src");
//                                    step = 2;
//                                }
//                            }, 2000);
//                        }
//                        if (step == 2) {
//                            handler.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    view.loadUrl("javascript:document.getElementsByTagName('a')[0].click();");
//                                    step = 3;
//                                }
//                            }, 2000);
//                        }
//                        if (step == 3) {
//                            handler.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    view.loadUrl("javascript:document.getElementById(\"mainBody\").getElementsByTagName('a')[0].click();");
//                                    view.loadUrl("javascript:document.getElementsByTagName('a')[1].click();");
//                                    clicked = true;
//                                }
//                            }, 2000);
//                        }
//                    }
                }
            });
            mWebGhost.setDownloadListener(new DownloadListener() {
                @Override
                public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

                }
            });
            mWebGhost.setWebChromeClient(new WebChromeClient() {
                boolean isSendLoadUrlOk;

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    if ((newProgress > 80 || newProgress == 100) && !isSendLoadUrlOk) {
                        isSendLoadUrlOk = true;
                        if (mCurrentGhostAd != null) {
                            ReportAgent.reportAdvShow(mCurrentGhostAd, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                        }
                    }
                }
            });
            WebSettings webSetting = mWebGhost.getSettings();
            webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);
            webSetting.setJavaScriptEnabled(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            webSetting.setAllowFileAccess(true);
            webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            webSetting.setSupportZoom(true);
            webSetting.setBuiltInZoomControls(false);
            webSetting.setUseWideViewPort(true);
            webSetting.setSupportMultipleWindows(false);
            webSetting.setJavaScriptEnabled(true);
            webSetting.setLoadWithOverviewMode(true);
            webSetting.setAppCacheEnabled(true);
            webSetting.setDatabaseEnabled(true);
            webSetting.setDomStorageEnabled(true);
            webSetting.setGeolocationEnabled(true);
            webSetting.setAppCacheMaxSize(5 * 1024 * 1024);
            webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
            webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
            webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0).getPath());
            webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
            webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        } catch (Exception e) {

        }
    }

    @Override
    public void onShowSelfAd(AdInfo adInfo) {
        if (selfAdDialog != null) {
            selfAdDialog.dismiss();
        }
        selfAdDialog = new PopFloatAdDialog(this);
        selfAdDialog.setAdInfo(adInfo);
        selfAdDialog.show();
        ReportAgent.reportAdvExtShow(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
    }
}
